"""
货物管理API路由
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, Query, status
from fastapi.responses import JSONResponse

from app.schemas.cargo import (
    CargoCreate, CargoUpdate, CargoResponse, CargoListResponse,
    CargoCategoryCreate, CargoCategoryUpdate, CargoCategoryResponse
)
from app.schemas.base import ResponseModel, PaginationParams
from app.services.cargo_service import CargoService, CargoCategoryService
from app.utils.dependencies import get_current_user
from app.models.user import User

router = APIRouter(prefix="/cargo", tags=["货物管理"])


# 货物分类相关路由
@router.post(
    "/categories",
    response_model=CargoCategoryResponse,
    status_code=status.HTTP_201_CREATED,
    summary="创建货物分类"
)
async def create_cargo_category(
    category_data: CargoCategoryCreate,
    current_user: User = Depends(get_current_user)
):
    """创建货物分类"""
    return await CargoCategoryService.create_category(category_data)


@router.get(
    "/categories/tree",
    response_model=List[CargoCategoryResponse],
    summary="获取分类树"
)
async def get_category_tree():
    """获取货物分类树"""
    return await CargoCategoryService.get_category_tree()


# 货物相关路由
@router.post(
    "/",
    response_model=CargoResponse,
    status_code=status.HTTP_201_CREATED,
    summary="创建货物"
)
async def create_cargo(
    cargo_data: CargoCreate,
    current_user: User = Depends(get_current_user)
):
    """创建货物"""
    return await CargoService.create_cargo(cargo_data)


@router.get(
    "/{cargo_id}",
    response_model=CargoResponse,
    summary="获取货物详情"
)
async def get_cargo(cargo_id: int):
    """获取货物详情"""
    return await CargoService.get_cargo(cargo_id)


@router.put(
    "/{cargo_id}",
    response_model=CargoResponse,
    summary="更新货物"
)
async def update_cargo(
    cargo_id: int,
    cargo_data: CargoUpdate,
    current_user: User = Depends(get_current_user)
):
    """更新货物"""
    return await CargoService.update_cargo(cargo_id, cargo_data)


@router.delete(
    "/{cargo_id}",
    response_model=ResponseModel,
    summary="删除货物"
)
async def delete_cargo(
    cargo_id: int,
    current_user: User = Depends(get_current_user)
):
    """删除货物"""
    success = await CargoService.delete_cargo(cargo_id)
    return ResponseModel(
        success=success,
        message="货物删除成功" if success else "货物删除失败"
    )


@router.get(
    "/",
    response_model=CargoListResponse,
    summary="获取货物列表"
)
async def list_cargos(
    page: int = Query(default=1, ge=1, description="页码"),
    size: int = Query(default=20, ge=1, le=100, description="每页数量"),
    category_id: Optional[int] = Query(default=None, description="分类ID"),
    status: Optional[str] = Query(default=None, description="状态"),
    search: Optional[str] = Query(default=None, description="搜索关键词")
):
    """获取货物列表"""
    cargos, total = await CargoService.list_cargos(
        page=page,
        size=size,
        category_id=category_id,
        status=status,
        search=search
    )
    
    pages = (total + size - 1) // size
    
    return CargoListResponse(
        items=cargos,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


@router.get(
    "/search/by-code/{code}",
    response_model=CargoResponse,
    summary="根据编码搜索货物"
)
async def search_cargo_by_code(code: str):
    """根据编码搜索货物"""
    from app.models.cargo import Cargo
    from fastapi import HTTPException
    
    cargo = await Cargo.get_or_none(code=code).prefetch_related("category")
    if not cargo:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="货物不存在"
        )
    
    return CargoResponse.from_orm(cargo)


@router.get(
    "/statistics/summary",
    summary="获取货物统计摘要"
)
async def get_cargo_statistics():
    """获取货物统计摘要"""
    from app.models.cargo import Cargo, CargoCategory
    
    try:
        # 总货物数量
        total_cargos = await Cargo.all().count()
        
        # 按状态统计
        status_stats = {}
        statuses = ["in_stock", "in_transit", "delivered", "damaged", "lost"]
        for status_val in statuses:
            count = await Cargo.filter(status=status_val).count()
            status_stats[status_val] = count
        
        # 按分类统计
        categories = await CargoCategory.all()
        category_stats = {}
        for category in categories:
            count = await Cargo.filter(category=category).count()
            category_stats[category.name] = count
        
        return {
            "total_cargos": total_cargos,
            "status_statistics": status_stats,
            "category_statistics": category_stats
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取统计数据失败"
        )
